"""
多格式导出器
提供PDF、Word、LaTeX等多种格式导出、格式保真度优化和导出质量验证功能
"""

import logging
import json
import os
import tempfile
import subprocess
import shutil
from typing import Dict, List, Optional, Any
from dataclasses import dataclass, field
from enum import Enum
import datetime
from pathlib import Path

from ..models.base_models import BaseModel
from .base_component import BaseComponent

logger = logging.getLogger(__name__)


class ExportFormat(Enum):
    """导出格式"""
    PDF = "pdf"
    DOCX = "docx"
    LATEX = "latex"
    HTML = "html"
    MARKDOWN = "markdown"
    RTF = "rtf"
    ODT = "odt"
    EPUB = "epub"
    PLAIN_TEXT = "txt"
    JSON = "json"


class QualityLevel(Enum):
    """质量等级"""
    DRAFT = "draft"
    STANDARD = "standard"
    HIGH = "high"
    PUBLICATION = "publication"


class PageSize(Enum):
    """页面大小"""
    A4 = "A4"
    LETTER = "Letter"
    LEGAL = "Legal"
    A3 = "A3"


@dataclass
class ExportSettings(BaseModel):
    """导出设置"""
    format: ExportFormat = ExportFormat.PDF
    quality: QualityLevel = QualityLevel.STANDARD
    page_size: PageSize = PageSize.A4
    page_orientation: str = "portrait"
    margins: Dict[str, float] = field(default_factory=lambda: {
        'top': 2.5, 'bottom': 2.5, 'left': 2.5, 'right': 2.5
    })
    font_family: str = "Times New Roman"
    font_size: int = 12
    line_spacing: float = 1.5
    include_toc: bool = True
    include_page_numbers: bool = True
    include_headers: bool = True
    include_footers: bool = True
    output_filename: str = ""
    output_directory: str = ""
    overwrite_existing: bool = False

@dataclass
class ExportResult(BaseModel):
    """导出结果"""
    success: bool = True
    error_message: str = ""
    output_path: str = ""
    file_size: int = 0
    format: ExportFormat = ExportFormat.PDF
    fidelity_score: float = 0.0
    quality_score: float = 0.0
    processing_time_ms: float = 0.0
    pages_generated: int = 0
    images_processed: int = 0
    tables_processed: int = 0
    validation_passed: bool = True
    validation_errors: List[str] = field(default_factory=list)
    validation_warnings: List[str] = field(default_factory=list)
    creation_time: datetime.datetime = field(default_factory=datetime.datetime.now)
    export_settings: Optional[ExportSettings] = None
    
    def get_file_size_mb(self) -> float:
        """获取文件大小（MB）"""
        return self.file_size / (1024 * 1024) if self.file_size > 0 else 0.0
    
    def get_processing_time_seconds(self) -> float:
        """获取处理时间（秒）"""
        return self.processing_time_ms / 1000.0


@dataclass
class DocumentContent(BaseModel):
    """文档内容"""
    title: str = ""
    subtitle: str = ""
    authors: List[str] = field(default_factory=list)
    abstract: str = ""
    keywords: List[str] = field(default_factory=list)
    sections: List[Dict[str, Any]] = field(default_factory=list)
    references: List[Dict[str, str]] = field(default_factory=list)
    citations: Dict[str, str] = field(default_factory=dict)
    figures: List[Dict[str, Any]] = field(default_factory=list)
    tables: List[Dict[str, Any]] = field(default_factory=list)
    appendices: List[Dict[str, Any]] = field(default_factory=list)
    metadata: Dict[str, Any] = field(default_factory=dict)
    
    def get_word_count(self) -> int:
        """获取总字数"""
        word_count = 0
        if self.title:
            word_count += len(self.title.split())
        if self.abstract:
            word_count += len(self.abstract.split())
        for section in self.sections:
            if 'content' in section:
                word_count += len(section['content'].split())
        return word_count
    
    def get_section_count(self) -> int:
        """获取章节数量"""
        return len(self.sections)


class MultiFormatExporter(BaseComponent):
    """多格式导出器"""
    
    def get_required_configs(self) -> List[str]:
        """获取必需的配置项"""
        return []
    
    def _setup_component(self):
        """设置组件特定的初始化逻辑"""
        self.logger.info("多格式导出器初始化")
        
        # 注册导出器
        self.exporters = {
            ExportFormat.PDF: self._export_to_pdf,
            ExportFormat.DOCX: self._export_to_docx,
            ExportFormat.LATEX: self._export_to_latex,
            ExportFormat.HTML: self._export_to_html,
            ExportFormat.MARKDOWN: self._export_to_markdown,
            ExportFormat.RTF: self._export_to_rtf,
            ExportFormat.ODT: self._export_to_odt,
            ExportFormat.EPUB: self._export_to_epub,
            ExportFormat.PLAIN_TEXT: self._export_to_text,
            ExportFormat.JSON: self._export_to_json
        }
        
        # 验证器
        self.validators = {
            ExportFormat.PDF: self._validate_pdf,
            ExportFormat.DOCX: self._validate_docx,
            ExportFormat.LATEX: self._validate_latex,
            ExportFormat.HTML: self._validate_html
        }
        
        # 模板管理
        self.templates = {}
        
        # 检查外部工具
        self.external_tools = self._check_external_tools()
        
        self.logger.info("多格式导出器初始化完成")    

    def export_document(self, 
                       content: DocumentContent,
                       settings: ExportSettings) -> ExportResult:
        """
        导出文档
        Args:
            content: 文档内容
            settings: 导出设置
        Returns:
            导出结果
        """
        try:
            start_time = datetime.datetime.now()
            
            # 验证输入
            if not content.title and not content.sections:
                raise ValueError("文档内容不能为空")
            
            # 准备输出路径
            output_path = self._prepare_output_path(settings)
            
            # 执行导出
            if settings.format in self.exporters:
                exporter = self.exporters[settings.format]
                result = exporter(content, settings, output_path)
            else:
                raise ValueError(f"不支持的导出格式: {settings.format}")
            
            # 计算处理时间
            processing_time = (datetime.datetime.now() - start_time).total_seconds() * 1000
            result.processing_time_ms = processing_time
            
            # 设置基本信息
            result.output_path = output_path
            result.format = settings.format
            result.export_settings = settings
            
            # 获取文件大小
            if os.path.exists(output_path):
                result.file_size = os.path.getsize(output_path)
            
            # 验证导出结果
            if settings.format in self.validators:
                validator = self.validators[settings.format]
                validation_result = validator(output_path, settings)
                result.validation_passed = validation_result['passed']
                result.validation_errors = validation_result.get('errors', [])
                result.validation_warnings = validation_result.get('warnings', [])
            
            # 计算质量评分
            result.fidelity_score = self._calculate_fidelity_score(content, result, settings)
            result.quality_score = self._calculate_quality_score(result, settings)
            
            self.logger.info(f"文档导出完成: {settings.format.value} (耗时: {processing_time:.2f}ms)")
            return result
            
        except Exception as e:
            self.logger.error(f"文档导出失败: {str(e)}")
            return ExportResult(
                success=False,
                error_message=str(e),
                format=settings.format
            )
    
    def batch_export(self, 
                    content: DocumentContent,
                    formats: List[ExportFormat],
                    base_settings: ExportSettings) -> Dict[ExportFormat, ExportResult]:
        """
        批量导出多种格式
        Args:
            content: 文档内容
            formats: 导出格式列表
            base_settings: 基础设置
        Returns:
            导出结果字典
        """
        results = {}
        
        for format_type in formats:
            try:
                # 复制设置并修改格式
                settings = ExportSettings(**base_settings.to_dict())
                settings.format = format_type
                
                # 调整格式特定的输出文件名
                if settings.output_filename:
                    base_name = os.path.splitext(settings.output_filename)[0]
                    extension = self._get_file_extension(format_type)
                    settings.output_filename = f"{base_name}.{extension}"
                
                # 执行导出
                result = self.export_document(content, settings)
                results[format_type] = result
                
            except Exception as e:
                self.logger.error(f"批量导出 {format_type.value} 失败: {str(e)}")
                results[format_type] = ExportResult(
                    success=False,
                    error_message=str(e),
                    format=format_type
                )
        
        return results    

    def get_supported_formats(self) -> List[Dict[str, Any]]:
        """获取支持的格式列表"""
        formats = []
        
        for format_enum in ExportFormat:
            format_info = {
                'format': format_enum.value,
                'name': self._get_format_name(format_enum),
                'description': self._get_format_description(format_enum),
                'extension': self._get_file_extension(format_enum),
                'supported': format_enum in self.exporters,
                'requires_external_tools': self._requires_external_tools(format_enum),
                'quality_levels': [q.value for q in QualityLevel]
            }
            formats.append(format_info)
        
        return formats
    
    # 具体导出方法
    def _export_to_pdf(self, 
                      content: DocumentContent,
                      settings: ExportSettings,
                      output_path: str) -> ExportResult:
        """导出为PDF"""
        try:
            # 简化实现：生成HTML然后转换为PDF
            html_content = self._generate_html_content(content, settings)
            
            # 使用简单的HTML到PDF转换
            return self._convert_html_to_pdf_simple(html_content, output_path, settings)
                
        except Exception as e:
            return ExportResult(
                success=False,
                error_message=f"PDF导出失败: {str(e)}"
            )
    
    def _export_to_docx(self, 
                       content: DocumentContent,
                       settings: ExportSettings,
                       output_path: str) -> ExportResult:
        """导出为Word文档"""
        try:
            # 简化实现：生成基本的Word文档结构
            docx_content = self._generate_docx_content(content, settings)
            
            with open(output_path, 'w', encoding='utf-8') as f:
                f.write(docx_content)
            
            return ExportResult(
                success=True,
                pages_generated=1,
                tables_processed=len(content.tables),
                images_processed=len(content.figures)
            )
            
        except Exception as e:
            return ExportResult(
                success=False,
                error_message=f"Word导出失败: {str(e)}"
            )
    
    def _export_to_latex(self, 
                        content: DocumentContent,
                        settings: ExportSettings,
                        output_path: str) -> ExportResult:
        """导出为LaTeX"""
        try:
            latex_content = self._generate_latex_content(content, settings)
            
            with open(output_path, 'w', encoding='utf-8') as f:
                f.write(latex_content)
            
            return ExportResult(success=True)
            
        except Exception as e:
            return ExportResult(
                success=False,
                error_message=f"LaTeX导出失败: {str(e)}"
            )
    
    def _export_to_html(self, 
                       content: DocumentContent,
                       settings: ExportSettings,
                       output_path: str) -> ExportResult:
        """导出为HTML"""
        try:
            html_content = self._generate_html_content(content, settings)
            
            with open(output_path, 'w', encoding='utf-8') as f:
                f.write(html_content)
            
            return ExportResult(
                success=True,
                images_processed=len(content.figures),
                tables_processed=len(content.tables)
            )
            
        except Exception as e:
            return ExportResult(
                success=False,
                error_message=f"HTML导出失败: {str(e)}"
            )
    
    def _export_to_markdown(self, 
                           content: DocumentContent,
                           settings: ExportSettings,
                           output_path: str) -> ExportResult:
        """导出为Markdown"""
        try:
            markdown_content = self._generate_markdown_content(content, settings)
            
            with open(output_path, 'w', encoding='utf-8') as f:
                f.write(markdown_content)
            
            return ExportResult(success=True)
            
        except Exception as e:
            return ExportResult(
                success=False,
                error_message=f"Markdown导出失败: {str(e)}"
            )    

    def _export_to_rtf(self, 
                      content: DocumentContent,
                      settings: ExportSettings,
                      output_path: str) -> ExportResult:
        """导出为RTF"""
        try:
            rtf_content = self._generate_rtf_content(content, settings)
            
            with open(output_path, 'w', encoding='utf-8') as f:
                f.write(rtf_content)
            
            return ExportResult(success=True)
            
        except Exception as e:
            return ExportResult(
                success=False,
                error_message=f"RTF导出失败: {str(e)}"
            )
    
    def _export_to_odt(self, 
                      content: DocumentContent,
                      settings: ExportSettings,
                      output_path: str) -> ExportResult:
        """导出为ODT"""
        try:
            # 简化实现：生成HTML并提示转换
            html_content = self._generate_html_content(content, settings)
            html_path = output_path.replace('.odt', '.html')
            
            with open(html_path, 'w', encoding='utf-8') as f:
                f.write(html_content)
            
            return ExportResult(
                success=True,
                validation_warnings=[
                    f"ODT格式需要手动转换，HTML文件已生成: {html_path}"
                ]
            )
            
        except Exception as e:
            return ExportResult(
                success=False,
                error_message=f"ODT导出失败: {str(e)}"
            )
    
    def _export_to_epub(self, 
                       content: DocumentContent,
                       settings: ExportSettings,
                       output_path: str) -> ExportResult:
        """导出为EPUB"""
        return ExportResult(
            success=False,
            error_message="EPUB格式暂未完全实现，建议使用HTML格式"
        )
    
    def _export_to_text(self, 
                       content: DocumentContent,
                       settings: ExportSettings,
                       output_path: str) -> ExportResult:
        """导出为纯文本"""
        try:
            text_content = self._generate_text_content(content)
            
            with open(output_path, 'w', encoding='utf-8') as f:
                f.write(text_content)
            
            return ExportResult(success=True)
            
        except Exception as e:
            return ExportResult(
                success=False,
                error_message=f"文本导出失败: {str(e)}"
            )
    
    def _export_to_json(self, 
                       content: DocumentContent,
                       settings: ExportSettings,
                       output_path: str) -> ExportResult:
        """导出为JSON"""
        try:
            json_data = content.to_dict()
            
            with open(output_path, 'w', encoding='utf-8') as f:
                json.dump(json_data, f, ensure_ascii=False, indent=2)
            
            return ExportResult(success=True)
            
        except Exception as e:
            return ExportResult(
                success=False,
                error_message=f"JSON导出失败: {str(e)}"
            )    
   
 # 内容生成方法
    def _generate_html_content(self, content: DocumentContent, settings: ExportSettings) -> str:
        """生成HTML内容"""
        html_parts = [
            '<!DOCTYPE html>',
            '<html lang="zh">',
            '<head>',
            '    <meta charset="UTF-8">',
            '    <meta name="viewport" content="width=device-width, initial-scale=1.0">',
            f'    <title>{content.title}</title>',
            '    <style>',
            f'        body {{ font-family: {settings.font_family}; font-size: {settings.font_size}pt; line-height: {settings.line_spacing}; }}',
            '        .title { text-align: center; font-size: 24pt; font-weight: bold; margin-bottom: 20px; }',
            '        .authors { text-align: center; margin-bottom: 20px; }',
            '        .abstract { margin: 20px 0; padding: 10px; background-color: #f5f5f5; }',
            '        .keywords { margin: 10px 0; font-style: italic; }',
            '        .section { margin: 20px 0; }',
            '        .section-title { font-weight: bold; font-size: 16pt; margin: 15px 0 10px 0; }',
            '        .references { margin-top: 30px; }',
            '        .reference { margin: 5px 0; }',
            '    </style>',
            '</head>',
            '<body>'
        ]
        
        # 添加标题
        if content.title:
            html_parts.append(f'    <div class="title">{content.title}</div>')
        
        # 添加作者
        if content.authors:
            html_parts.append(f'    <div class="authors">{", ".join(content.authors)}</div>')
        
        # 添加摘要
        if content.abstract:
            html_parts.extend([
                '    <div class="abstract">',
                '        <strong>Abstract:</strong>',
                f'        <p>{content.abstract}</p>',
                '    </div>'
            ])
        
        # 添加关键词
        if content.keywords:
            html_parts.append(f'    <div class="keywords"><strong>Keywords:</strong> {", ".join(content.keywords)}</div>')
        
        # 添加章节
        for section in content.sections:
            html_parts.append('    <div class="section">')
            if 'title' in section:
                html_parts.append(f'        <div class="section-title">{section["title"]}</div>')
            if 'content' in section:
                paragraphs = section['content'].split('\n\n')
                for para in paragraphs:
                    if para.strip():
                        html_parts.append(f'        <p>{para.strip()}</p>')
            html_parts.append('    </div>')
        
        # 添加参考文献
        if content.references:
            html_parts.extend([
                '    <div class="references">',
                '        <div class="section-title">References</div>'
            ])
            for i, ref in enumerate(content.references, 1):
                ref_text = ref.get('text', str(ref))
                html_parts.append(f'        <div class="reference">[{i}] {ref_text}</div>')
            html_parts.append('    </div>')
        
        html_parts.extend([
            '</body>',
            '</html>'
        ])
        
        return '\n'.join(html_parts)
    
    def _generate_markdown_content(self, content: DocumentContent, settings: ExportSettings) -> str:
        """生成Markdown内容"""
        md_parts = []
        
        # 添加标题
        if content.title:
            md_parts.extend([
                f'# {content.title}',
                ''
            ])
        
        # 添加作者
        if content.authors:
            md_parts.extend([
                f'**Authors:** {", ".join(content.authors)}',
                ''
            ])
        
        # 添加摘要
        if content.abstract:
            md_parts.extend([
                '## Abstract',
                '',
                content.abstract,
                ''
            ])
        
        # 添加关键词
        if content.keywords:
            md_parts.extend([
                f'**Keywords:** {", ".join(content.keywords)}',
                ''
            ])
        
        # 添加章节
        for section in content.sections:
            if 'title' in section:
                level = section.get('level', 1)
                header_prefix = '#' * (level + 1)
                md_parts.extend([
                    f'{header_prefix} {section["title"]}',
                    ''
                ])
            
            if 'content' in section:
                md_parts.extend([
                    section['content'],
                    ''
                ])
        
        # 添加参考文献
        if content.references:
            md_parts.extend([
                '## References',
                ''
            ])
            for i, ref in enumerate(content.references, 1):
                ref_text = ref.get('text', str(ref))
                md_parts.append(f'{i}. {ref_text}')
            md_parts.append('')
        
        return '\n'.join(md_parts)  
  
    def _generate_latex_content(self, content: DocumentContent, settings: ExportSettings) -> str:
        """生成LaTeX内容"""
        latex_parts = [
            '\\documentclass[12pt,a4paper]{article}',
            '\\usepackage[utf8]{inputenc}',
            '\\usepackage{amsmath}',
            '\\usepackage{amsfonts}',
            '\\usepackage{amssymb}',
            '\\usepackage{graphicx}',
            '\\usepackage{hyperref}',
            '',
            '\\begin{document}',
            ''
        ]
        
        # 添加标题
        if content.title:
            latex_parts.extend([
                f'\\title{{{content.title}}}',
                ''
            ])
        
        # 添加作者
        if content.authors:
            authors_latex = ' \\and '.join(content.authors)
            latex_parts.extend([
                f'\\author{{{authors_latex}}}',
                ''
            ])
        
        # 生成标题页
        if content.title or content.authors:
            latex_parts.extend([
                '\\maketitle',
                ''
            ])
        
        # 添加摘要
        if content.abstract:
            latex_parts.extend([
                '\\begin{abstract}',
                content.abstract,
                '\\end{abstract}',
                ''
            ])
        
        # 添加关键词
        if content.keywords:
            latex_parts.extend([
                f'\\textbf{{Keywords:}} {", ".join(content.keywords)}',
                '',
                '\\newpage',
                ''
            ])
        
        # 添加目录
        if settings.include_toc:
            latex_parts.extend([
                '\\tableofcontents',
                '\\newpage',
                ''
            ])
        
        # 添加章节
        for section in content.sections:
            if 'title' in section:
                level = section.get('level', 1)
                if level == 1:
                    latex_parts.append(f'\\section{{{section["title"]}}}')
                elif level == 2:
                    latex_parts.append(f'\\subsection{{{section["title"]}}}')
                elif level == 3:
                    latex_parts.append(f'\\subsubsection{{{section["title"]}}}')
                latex_parts.append('')
            
            if 'content' in section:
                content_text = self._escape_latex(section['content'])
                latex_parts.extend([
                    content_text,
                    ''
                ])
        
        # 添加参考文献
        if content.references:
            latex_parts.extend([
                '\\begin{thebibliography}{99}',
                ''
            ])
            for i, ref in enumerate(content.references, 1):
                ref_text = self._escape_latex(ref.get('text', str(ref)))
                latex_parts.append(f'\\bibitem{{ref{i}}} {ref_text}')
            latex_parts.extend([
                '',
                '\\end{thebibliography}',
                ''
            ])
        
        latex_parts.extend([
            '\\end{document}'
        ])
        
        return '\n'.join(latex_parts)
    
    def _generate_rtf_content(self, content: DocumentContent, settings: ExportSettings) -> str:
        """生成RTF内容"""
        rtf_parts = [
            '{\\rtf1\\ansi\\deff0',
            '{\\fonttbl{\\f0 Times New Roman;}}',
            '\\f0\\fs24'
        ]
        
        # 添加标题
        if content.title:
            rtf_parts.extend([
                '\\qc\\b\\fs32',
                content.title,
                '\\par\\par'
            ])
        
        # 添加作者
        if content.authors:
            rtf_parts.extend([
                '\\qc\\fs24',
                ', '.join(content.authors),
                '\\par\\par'
            ])
        
        # 重置格式
        rtf_parts.append('\\ql\\b0\\fs24')
        
        # 添加摘要
        if content.abstract:
            rtf_parts.extend([
                '\\b Abstract:\\b0\\par',
                content.abstract,
                '\\par\\par'
            ])
        
        # 添加关键词
        if content.keywords:
            rtf_parts.extend([
                f'\\b Keywords:\\b0 {", ".join(content.keywords)}',
                '\\par\\par'
            ])
        
        # 添加章节
        for section in content.sections:
            if 'title' in section:
                rtf_parts.extend([
                    '\\b\\fs28',
                    section['title'],
                    '\\b0\\fs24\\par\\par'
                ])
            
            if 'content' in section:
                rtf_parts.extend([
                    section['content'],
                    '\\par\\par'
                ])
        
        # 添加参考文献
        if content.references:
            rtf_parts.extend([
                '\\b\\fs28 References\\b0\\fs24\\par\\par'
            ])
            for i, ref in enumerate(content.references, 1):
                ref_text = ref.get('text', str(ref))
                rtf_parts.extend([
                    f'[{i}] {ref_text}',
                    '\\par'
                ])
        
        rtf_parts.append('}')
        return ''.join(rtf_parts)
    
    def _generate_text_content(self, content: DocumentContent) -> str:
        """生成纯文本内容"""
        text_parts = []
        
        # 添加标题
        if content.title:
            text_parts.extend([
                content.title.upper(),
                '=' * len(content.title),
                ''
            ])
        
        # 添加作者
        if content.authors:
            text_parts.extend([
                f'Authors: {", ".join(content.authors)}',
                ''
            ])
        
        # 添加摘要
        if content.abstract:
            text_parts.extend([
                'ABSTRACT',
                '-' * 8,
                content.abstract,
                ''
            ])
        
        # 添加关键词
        if content.keywords:
            text_parts.extend([
                f'Keywords: {", ".join(content.keywords)}',
                ''
            ])
        
        # 添加章节
        for section in content.sections:
            if 'title' in section:
                level = section.get('level', 1)
                title = section['title'].upper() if level == 1 else section['title']
                text_parts.extend([
                    title,
                    '-' * len(section['title']) if level == 1 else '',
                    ''
                ])
            
            if 'content' in section:
                text_parts.extend([
                    section['content'],
                    ''
                ])
        
        # 添加参考文献
        if content.references:
            text_parts.extend([
                'REFERENCES',
                '-' * 10,
                ''
            ])
            for i, ref in enumerate(content.references, 1):
                ref_text = ref.get('text', str(ref))
                text_parts.append(f'[{i}] {ref_text}')
            text_parts.append('')
        
        return '\n'.join(text_parts)
    
    def _generate_docx_content(self, content: DocumentContent, settings: ExportSettings) -> str:
        """生成Word文档内容（简化实现）"""
        # 这是一个简化的实现，实际应该使用python-docx库
        docx_parts = []
        
        if content.title:
            docx_parts.append(f"Title: {content.title}")
        
        if content.authors:
            docx_parts.append(f"Authors: {', '.join(content.authors)}")
        
        if content.abstract:
            docx_parts.extend([
                "",
                "Abstract:",
                content.abstract
            ])
        
        if content.keywords:
            docx_parts.append(f"Keywords: {', '.join(content.keywords)}")
        
        for section in content.sections:
            if 'title' in section:
                docx_parts.extend(["", section['title']])
            if 'content' in section:
                docx_parts.append(section['content'])
        
        if content.references:
            docx_parts.extend(["", "References:"])
            for i, ref in enumerate(content.references, 1):
                ref_text = ref.get('text', str(ref))
                docx_parts.append(f"[{i}] {ref_text}")
        
        return '\n'.join(docx_parts)
    
    # 辅助方法
    def _prepare_output_path(self, settings: ExportSettings) -> str:
        """准备输出路径"""
        if settings.output_filename:
            if settings.output_directory:
                output_path = os.path.join(settings.output_directory, settings.output_filename)
            else:
                output_path = settings.output_filename
        else:
            # 生成默认文件名
            timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
            extension = self._get_file_extension(settings.format)
            filename = f'document_{timestamp}.{extension}'
            
            if settings.output_directory:
                output_path = os.path.join(settings.output_directory, filename)
            else:
                output_path = filename
        
        # 确保目录存在
        output_dir = os.path.dirname(output_path)
        if output_dir and not os.path.exists(output_dir):
            os.makedirs(output_dir, exist_ok=True)
        
        # 检查文件是否存在
        if os.path.exists(output_path) and not settings.overwrite_existing:
            base, ext = os.path.splitext(output_path)
            counter = 1
            while os.path.exists(f"{base}_{counter}{ext}"):
                counter += 1
            output_path = f"{base}_{counter}{ext}"
        
        return output_path    
  
  def _get_file_extension(self, format_type: ExportFormat) -> str:
        """获取文件扩展名"""
        extension_map = {
            ExportFormat.PDF: 'pdf',
            ExportFormat.DOCX: 'docx',
            ExportFormat.LATEX: 'tex',
            ExportFormat.HTML: 'html',
            ExportFormat.MARKDOWN: 'md',
            ExportFormat.RTF: 'rtf',
            ExportFormat.ODT: 'odt',
            ExportFormat.EPUB: 'epub',
            ExportFormat.PLAIN_TEXT: 'txt',
            ExportFormat.JSON: 'json'
        }
        return extension_map.get(format_type, 'txt')
    
    def _get_format_name(self, format_type: ExportFormat) -> str:
        """获取格式名称"""
        name_map = {
            ExportFormat.PDF: 'PDF文档',
            ExportFormat.DOCX: 'Word文档',
            ExportFormat.LATEX: 'LaTeX源码',
            ExportFormat.HTML: 'HTML网页',
            ExportFormat.MARKDOWN: 'Markdown文档',
            ExportFormat.RTF: 'RTF富文本',
            ExportFormat.ODT: 'OpenDocument文本',
            ExportFormat.EPUB: 'EPUB电子书',
            ExportFormat.PLAIN_TEXT: '纯文本',
            ExportFormat.JSON: 'JSON数据'
        }
        return name_map.get(format_type, '未知格式')
    
    def _get_format_description(self, format_type: ExportFormat) -> str:
        """获取格式描述"""
        desc_map = {
            ExportFormat.PDF: '便携式文档格式，适合打印和分享',
            ExportFormat.DOCX: 'Microsoft Word文档格式',
            ExportFormat.LATEX: 'LaTeX排版系统源码',
            ExportFormat.HTML: '超文本标记语言，适合网页展示',
            ExportFormat.MARKDOWN: '轻量级标记语言',
            ExportFormat.RTF: '富文本格式，跨平台兼容',
            ExportFormat.ODT: 'OpenDocument文本格式',
            ExportFormat.EPUB: '电子书标准格式',
            ExportFormat.PLAIN_TEXT: '纯文本格式，最大兼容性',
            ExportFormat.JSON: 'JSON数据格式，便于程序处理'
        }
        return desc_map.get(format_type, '未知格式')
    
    def _requires_external_tools(self, format_type: ExportFormat) -> bool:
        """检查是否需要外部工具"""
        external_required = {
            ExportFormat.PDF: True,  # 需要wkhtmltopdf或LaTeX
            ExportFormat.LATEX: True,  # 需要LaTeX引擎
            ExportFormat.ODT: True,  # 需要LibreOffice
            ExportFormat.EPUB: True  # 需要专门的EPUB工具
        }
        return external_required.get(format_type, False)
    
    def _check_external_tools(self) -> Dict[str, bool]:
        """检查外部工具可用性"""
        tools = {}
        
        # 检查常用工具
        tool_commands = {
            'pandoc': ['pandoc', '--version'],
            'wkhtmltopdf': ['wkhtmltopdf', '--version'],
            'pdflatex': ['pdflatex', '--version'],
            'xelatex': ['xelatex', '--version'],
            'lualatex': ['lualatex', '--version'],
            'libreoffice': ['libreoffice', '--version']
        }
        
        for tool_name, command in tool_commands.items():
            try:
                result = subprocess.run(command, capture_output=True, text=True, timeout=10)
                tools[tool_name] = result.returncode == 0
            except (subprocess.TimeoutExpired, FileNotFoundError, subprocess.SubprocessError):
                tools[tool_name] = False
        
        return tools
    
    def _escape_latex(self, text: str) -> str:
        """转义LaTeX特殊字符"""
        if not text:
            return text
        
        # LaTeX特殊字符映射
        escape_map = {
            '\\': '\\textbackslash{}',
            '{': '\\{',
            '}': '\\}',
            '$': '\\$',
            '&': '\\&',
            '%': '\\%',
            '#': '\\#',
            '^': '\\textasciicircum{}',
            '_': '\\_',
            '~': '\\textasciitilde{}'
        }
        
        for char, escaped in escape_map.items():
            text = text.replace(char, escaped)
        
        return text
    
    def _convert_html_to_pdf_simple(self, 
                                   html_content: str,
                                   output_path: str,
                                   settings: ExportSettings) -> ExportResult:
        """简单的HTML到PDF转换"""
        try:
            # 创建临时HTML文件
            with tempfile.NamedTemporaryFile(mode='w', suffix='.html', delete=False, encoding='utf-8') as temp_html:
                temp_html.write(html_content)
                temp_html_path = temp_html.name
            
            # 简化实现：复制HTML文件作为"PDF"（实际上仍是HTML）
            # 在实际应用中，这里应该使用真正的PDF转换工具
            shutil.copy2(temp_html_path, output_path.replace('.pdf', '.html'))
            
            # 清理临时文件
            os.unlink(temp_html_path)
            
            return ExportResult(
                success=True,
                validation_warnings=["PDF转换使用简化实现，实际生成HTML文件"]
            )
            
        except Exception as e:
            return ExportResult(
                success=False,
                error_message=f"HTML到PDF转换失败: {str(e)}"
            ) 
   
    # 验证方法
    def _validate_pdf(self, output_path: str, settings: ExportSettings) -> Dict[str, Any]:
        """验证PDF文件"""
        result = {
            'passed': True,
            'errors': [],
            'warnings': []
        }
        
        try:
            if not os.path.exists(output_path):
                result['passed'] = False
                result['errors'].append('PDF文件不存在')
                return result
            
            file_size = os.path.getsize(output_path)
            if file_size == 0:
                result['passed'] = False
                result['errors'].append('PDF文件为空')
            elif file_size < 100:
                result['warnings'].append('PDF文件过小，可能不完整')
            
        except Exception as e:
            result['passed'] = False
            result['errors'].append(f'PDF验证失败: {str(e)}')
        
        return result
    
    def _validate_docx(self, output_path: str, settings: ExportSettings) -> Dict[str, Any]:
        """验证Word文档"""
        result = {
            'passed': True,
            'errors': [],
            'warnings': []
        }
        
        try:
            if not os.path.exists(output_path):
                result['passed'] = False
                result['errors'].append('Word文档不存在')
                return result
            
            # 简化验证：检查文件大小
            file_size = os.path.getsize(output_path)
            if file_size == 0:
                result['passed'] = False
                result['errors'].append('Word文档为空')
            
        except Exception as e:
            result['passed'] = False
            result['errors'].append(f'Word文档验证失败: {str(e)}')
        
        return result
    
    def _validate_latex(self, output_path: str, settings: ExportSettings) -> Dict[str, Any]:
        """验证LaTeX文件"""
        result = {
            'passed': True,
            'errors': [],
            'warnings': []
        }
        
        try:
            if not os.path.exists(output_path):
                result['passed'] = False
                result['errors'].append('LaTeX文件不存在')
                return result
            
            # 检查LaTeX语法
            with open(output_path, 'r', encoding='utf-8') as f:
                content = f.read()
                
                if '\\documentclass' not in content:
                    result['errors'].append('缺少\\documentclass声明')
                    result['passed'] = False
                
                if '\\begin{document}' not in content:
                    result['errors'].append('缺少\\begin{document}')
                    result['passed'] = False
                
                if '\\end{document}' not in content:
                    result['errors'].append('缺少\\end{document}')
                    result['passed'] = False
            
        except Exception as e:
            result['passed'] = False
            result['errors'].append(f'LaTeX验证失败: {str(e)}')
        
        return result
    
    def _validate_html(self, output_path: str, settings: ExportSettings) -> Dict[str, Any]:
        """验证HTML文件"""
        result = {
            'passed': True,
            'errors': [],
            'warnings': []
        }
        
        try:
            if not os.path.exists(output_path):
                result['passed'] = False
                result['errors'].append('HTML文件不存在')
                return result
            
            # 检查HTML结构
            with open(output_path, 'r', encoding='utf-8') as f:
                content = f.read()
                
                if '<html' not in content:
                    result['warnings'].append('缺少<html>标签')
                
                if '<head>' not in content:
                    result['warnings'].append('缺少<head>标签')
                
                if '<body>' not in content:
                    result['warnings'].append('缺少<body>标签')
            
        except Exception as e:
            result['passed'] = False
            result['errors'].append(f'HTML验证失败: {str(e)}')
        
        return result
    
    def _calculate_fidelity_score(self, 
                                 content: DocumentContent,
                                 result: ExportResult,
                                 settings: ExportSettings) -> float:
        """计算保真度评分"""
        try:
            score = 1.0
            
            # 基于格式特性调整评分
            if settings.format == ExportFormat.PLAIN_TEXT:
                score *= 0.6  # 纯文本丢失格式信息
            elif settings.format == ExportFormat.MARKDOWN:
                score *= 0.8  # Markdown保留部分格式
            elif settings.format == ExportFormat.HTML:
                score *= 0.9  # HTML保留大部分格式
            elif settings.format == ExportFormat.PDF:
                score *= 0.95  # PDF保真度最高
            
            # 基于内容复杂度调整
            if content.figures:
                if settings.format in [ExportFormat.PLAIN_TEXT, ExportFormat.MARKDOWN]:
                    score *= 0.7  # 图片处理能力有限
            
            if content.tables:
                if settings.format == ExportFormat.PLAIN_TEXT:
                    score *= 0.5  # 表格格式丢失严重
            
            return max(0.0, min(1.0, score))
            
        except Exception as e:
            self.logger.error(f"保真度评分计算失败: {str(e)}")
            return 0.5
    
    def _calculate_quality_score(self, 
                                result: ExportResult,
                                settings: ExportSettings) -> float:
        """计算质量评分"""
        try:
            score = 1.0
            
            # 基于验证结果调整
            if not result.validation_passed:
                score *= 0.5
            
            # 基于错误数量调整
            error_count = len(result.validation_errors)
            if error_count > 0:
                score *= max(0.1, 1.0 - error_count * 0.1)
            
            # 基于警告数量调整
            warning_count = len(result.validation_warnings)
            if warning_count > 0:
                score *= max(0.5, 1.0 - warning_count * 0.05)
            
            # 基于质量设置调整
            quality_multiplier = {
                QualityLevel.DRAFT: 0.7,
                QualityLevel.STANDARD: 0.8,
                QualityLevel.HIGH: 0.9,
                QualityLevel.PUBLICATION: 1.0
            }
            score *= quality_multiplier.get(settings.quality, 0.8)
            
            return max(0.0, min(1.0, score))
            
        except Exception as e:
            self.logger.error(f"质量评分计算失败: {str(e)}")
            return 0.5